﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Dycox.Windows.Forms
{
    public class DataListViewItem : ListViewItem
    {
        public DataListViewItem(object dataItem)
            : this()
        {
            DataItem = dataItem;
        }

        public DataListViewItem()
        {

        }

        private object _dataItem;

        public object DataItem
        {
            get { return _dataItem; }
            set
            {
                if (_dataItem != value)
                {
                    _dataItem = value;
                    if (this.ListView != null ) PerformDataBinding();
                }
            }
        }

        internal void PerformDataBinding()
        {
            ListView lv = this.ListView;

            if (lv == null)
                throw new InvalidOperationException("DataListViewItem did not belong to any ListView control.");

            foreach (ColumnHeader col in lv.Columns)
            {
                DataColumnHeader dcol = col as DataColumnHeader;
                string text ;

                if (_dataItem != null && dcol != null)
                {
                    try
                    {
                        text = dcol.GetValueString(_dataItem);
                    }
                    catch(Exception ex)
                    {
                        text = "ERROR: " + ex.Message;
                    }
                }
                else
                    text = null;

                int index = col.Index;
                if (index > 0)
                {
                    if (index < SubItems.Count)
                        SubItems[index].Text = text;
                    else
                    {
                        do
                        {
                            SubItems.Add(text);
                        } while (index >= SubItems.Count);
                    }
                    
                }
                else
                    this.Text = text;
            }

            DataListView dlv = lv as DataListView;
            if (dlv != null)
            {
                string member = dlv.ImageKeyDataMember;
                if (!string.IsNullOrWhiteSpace(member))
                {
                    object value = Dycox.Utils.DataBinderUtil.Eval(_dataItem, member);
                    if (value == null)
                        this.ImageKey = null;
                    else if (value is string)
                        this.ImageKey = (string)value;
                    else if (value is int)
                        this.ImageIndex = (int)value;
                    else
                        this.ImageKey = value.ToString();
                }
            }
        }
    }
}
